// 进入这个页面的时候创建websocket连接[整个页面随时使用]
function connectSocketInit(GroupID, UserID) {

	var url = 'wss://api.meimo.comdns.cn/wss';

	uni.closeSocket() //创建新的socket连接前确保旧的已关闭

	//创建一个socket连接
	uni.connectSocket({
		url: url,
		success: res => {
			// console.log('创建一个新连接！');
		}
	})
	//监听socket打开
	uni.onSocketOpen((res) => {
		// this.isSocketOpen=true
		// console.log('监听socket已打开！', res);
	})
	//监听socket关闭
	uni.onSocketClose((res) => {
		// this.isSocketOpen=false
		// console.log('监听socket已关闭！',res);
	})
	//监听socket错误
	uni.onSocketError(() => {
		// this.isSocketOpen=false
		// console.log('WebSocket连接打开失败');
	})

	//监听socket消息
	uni.onSocketMessage((res) => {
		// 退出后，关闭连接
		// let supplierData = uni.getStorageSync("supplier");
		// if(supplierData == "") {
		// 	uni.closeSocket()
		// }

		// console.log("监听返回", res);

		if (res.data == "connectok") { //判断消息类型是否为用来监听链接的ping，如果是则不继续执行只是控制台显示

			// // console.log("连接成功");
			let GroupInfo = {
				"Act": "joinGroup",
				"GroupID": 0,
				"UserID": UserID,
				"SendType": 0,
				"SendData": "上线了"
			}

			// let GroupInfo = "joinGroup|0|" + UserID + "|上线了";
			uni.sendSocketMessage({
				data: JSON.stringify(GroupInfo),
				success: () => {},
				fail: () => {
					// this.isSocketOpen=false
				}
			});
			return false;
		}

		if (res.data == "pong") {
			// console.log('保持在线')
			// return res.data;
		}

		// if ( res.data == "joinGroup" || res.data == "连接握手成功！") {


		// 	let GroupInfo = "sendToGroup|0|" + UserID + "|保持在线";

		// 	uni.sendSocketMessage({
		// 		data: GroupInfo,
		// 		success:()=>{},
		// 		fail:()=>{
		// 			// this.isSocketOpen=false
		// 		}
		// 	});
		// 	return false;
		// }

	})

	//先确保清除了之前的心跳定时器
	clearInterval(pingpangTimes);

	//每过一段时间发送一次心跳，发送Ping,服务器会反馈pong，这样操作以保持socket一直是连接状态，防止断开连接，心跳停止
	const pingpangTimes = setInterval(() => {
		let GroupInfo = {
			"Act": "ping",
			"GroupID": 0,
			"UserID": UserID,
			"SendType": 0,
			"SendData": "ping"
		}

		// let GroupInfo = "ping|0|" + UserID + "|ping"

		uni.sendSocketMessage({
			data: JSON.stringify(GroupInfo),
			success: () => {
				// // console.log('20秒心跳')
			},
			fail: () => {
				// this.isSocketOpen=false
			}
		});
	}, 20000)

}

function sendMessage(Act, GroupID, UserID, SendType, UpMsgID, SendData) {
	let GroupInfo = {
		"Act": Act,
		"GroupID": GroupID,
		"UserID": UserID,
		"SendType": SendType,
		"UpMsgID": UpMsgID,
		"SendData": SendData
	}

	// console.log('发出信息之前：', JSON.stringify(GroupInfo));
	// let GroupInfo = Act + "|" + GroupID + "|" + UserID + "|" + SendData

	uni.sendSocketMessage({
		data: JSON.stringify(GroupInfo),
		success: (res) => {
			// console.log('发出信息：', JSON.stringify(GroupInfo));
		},
		fail: () => {
			// this.isSocketOpen=false
		}
	});
}


module.exports = {
	connectSocketInit,
	sendMessage
}